package com.evaluation.kexingcp.psycho.evaluation.sys.evaluation

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.evaluation.kexingcp.admin.api.entity.SysMessageEntity
import com.evaluation.kexingcp.admin.api.vo.OrgTreeVO
import com.evaluation.kexingcp.admin.api.vo.SysMessageVO
import com.evaluation.kexingcp.admin.service.SysMessageService
import com.evaluation.kexingcp.common.core.constant.CacheConstants
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationTaskService
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationTaskUserRelService
import com.evaluation.kexingcp.psycho.evaluation.sys.sms.SmsServiceImpl
import jakarta.annotation.PostConstruct
import org.slf4j.LoggerFactory
import org.springframework.data.redis.connection.Message
import org.springframework.data.redis.connection.MessageListener
import org.springframework.data.redis.listener.ChannelTopic
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.stereotype.Service

// 主要处理用户作业完成的数据统计

@Service
open class EvaluationNotifyService(
    private val listenerContainer: RedisMessageListenerContainer,
    private val sysMessageService: SysMessageService,
    private val evaluationService: EvaluationService,
) {

    private val log = LoggerFactory.getLogger(EvaluationNotifyService::class.java)

    @PostConstruct
    open fun afterPropertiesSet() {
        listenerContainer.addMessageListener( object : MessageListener {
            override fun onMessage(message: Message, pattern: ByteArray?) {
                log.info("任务完成信息得日志来了 {}", message)
                // 开始统计数据操作，因为是一台服务器，直接开启线程同步，统计数据
                synchronized(this) {
                    try {

                        evaluationService.generateReport();

                    } catch (e: Exception) {
                        log.error("任务完成统计数据失败", e)
                    }
                }
            }
        }, ChannelTopic.of(EVALUATION_CHANNEL))
    }


    fun sendSiteMessage(title: String, notifyUserIds: List<Long>) {
        // 生成站内信
        val sysMessageVO = SysMessageVO()
        sysMessageVO.title = title
        sysMessageVO.content = title
        sysMessageVO.allFlag = "0"
        sysMessageVO.category = "1"
        sysMessageVO.sort = 0
        sysMessageVO.userList = notifyUserIds.map { id -> OrgTreeVO().also { it.id = id } }

        sysMessageService.saveOrUpdateMessage(sysMessageVO)
        val message = sysMessageService
            .getOne(QueryWrapper<SysMessageEntity>().eq("send_flag", "0").orderByDesc("create_time"), false)
        if (message != null) {
            sysMessageService.sendMessage(message.id)
        }
    }
}